import collections
import threading
import queue
# ----------------------------------------
try:
    from .job import Job
except:
    from job import Job
# --------------------------------------------------


class JobManager:

    def __init__(self):
        self._jobs = collections.OrderedDict()
        self._jobslock = threading.RLock()
        self._signals = queue.Queue()
        self._status = False

    def add_job(self, job_id):
        with self._jobslock:
            # --------------------------------------------------
            job = self._jobs.get(job_id)
            if not job:
                job = Job(job_id)
                self._jobs[job_id] = job
            # --------------------------------------------------
            return job

    def ls_jobs(self):
        with self._jobslock:
            return self._jobs.keys()

    def select_job(self, job_id):
        with self._jobslock:
            return self._jobs.get(job_id)

    def rm_job(self, job_id):
        with self._jobslock:
            # --------------------------------------------------
            if job_id in self._jobs:
                del self._jobs[job_id]

    def _worker(self, callback, *args, **kwargs):
        while self._status:
            signal = self._signals.get()
            job_id, sign = signal
            # --------------------------------------------------
            if sign == -1:
                self.rm_job(job_id)
            # ----------------------------------------
            else:
                callback(signal, *args, **kwargs)
            # --------------------------------------------------
            self._signals.task_done()

    def run(self, callback, args=(), kwargs=None):
        self._status = True
        threading.Thread(daemon=True, target=self._worker,
                         args=(callback,)+args, kwargs=kwargs).start()

    def stop(self):
        pass


if __name__ == '__main__':
    job_mgr = JobManager()
